package controllers;


import java.util.*;
import play.Logger;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.Result;

public class LogSession extends Action.Simple {

	private static HashMap<String, String> loginSessions;
	private static HashMap<String, Integer> loggedSpecials;

	static {
		loginSessions = new HashMap<String, String>();
		loggedSpecials = new HashMap<String, Integer>();
	}

    public Result call(Http.Context ctx) throws Throwable {

		String uuid = ctx.session().get("uuid");
				
		if (uuid != null)
		{
			String username = getUsernameFromUUID(uuid);
			Integer role = getRoleFromUUID(uuid);
			if (username != null)
				ctx.args.put("username", username);											
			if (role != null)
				ctx.args.put("role", role);
		}

        return delegate.call(ctx);
    }

    public static String current() {
		return (String)Http.Context.current().args.get("username");
    }
	
	public static Integer currentRole() {
		return (Integer)Http.Context.current().args.get("role");
	}

	public static String createSession(String username, Integer role) {
		String uuid = java.util.UUID.randomUUID().toString();
		loginSessions.put(uuid, username);		
		if (role > 0)
			loggedSpecials.put(uuid, role);
		return uuid;
	}	
	
	public static void destroySession(String uuid) {
		loginSessions.remove(uuid);	
		loggedSpecials.remove(uuid);
	}
	
	public static String getUsernameFromUUID(String uuid) {
		return loginSessions.get(uuid);	
	}	
	
	public static Integer getRoleFromUUID(String uuid) {
		return loggedSpecials.get(uuid);
	}
	
	public static boolean isUserAlreadyLogin(String username){
		return loginSessions.containsValue(username);
	}
}